import nmap
import socket
import re
import subprocess
smbos = re.compile('OS: (.+)\n')
nbname = re.compile('(NetBIOS name.+)')

def nbscan(ip):
    nm = nmap.PortScanner()
    nm.scan(hosts = ip, arguments = '-p T:139 --script nbstat.nse' )
    if 'hostscript' not in nm[ip].keys():
        raise Exception('No nbscan results')
        
    for scriptinfo in nm[ip]['hostscript']:
        if scriptinfo['id'] == 'nbstat':
            nbinfo = scriptinfo['output'] 
            match = nbname.search(nbinfo)
            if match:
                return {'info': nbinfo, 'nbname' : str(match.group(1))}
            else:
                return {'info': nbinfo, 'nbname' : 'None'}
        else:
            raise Exception('No nbscan results')
            
def smbscan(ip):
    nm = nmap.PortScanner()
    nm.scan(hosts = ip, arguments = '-p T:139,445 --script smb-os-discovery.nse' )
    if 'hostscript' not in nm[ip].keys():
        raise Exception('No smbscan results')
        
    for scriptinfo in nm[ip]['hostscript']:
        if scriptinfo['id'] == 'smb-os-discovery':
            smbinfo = scriptinfo['output']
            match = smbos.search(smbinfo)
            if match:
                return {'info' : smbinfo, 'smbos' : str(match.group(1))}
            else:
                return {'info' : smbinfo, 'smbos' : 'None'}
        else:
            raise Exception('No smbcan results')
            
def dnsresolve(ip):
    return socket.gethostbyaddr(ip)[0]
    
    
def xml_to_html(xmlfile, htmlfile):
    command = 'xsltproc {} -o {}'.format(xmlfile, htmlfile)
    try:
        result = subprocess.call(command, shell=True)
    except subprocess.CalledProcessError as e:
        logging.error('Command execution failed. Returned status: %s. Exiting...', e.returncode)
        raise